package com.nulldev.util.web.YouTubeExtractor.endscreen;

import java.text.DecimalFormat;

import com.nulldev.util.VariableAPI.ArrayUtils;
import com.nulldev.util.VariableAPI.MathUtil;
import com.nulldev.util.VariableAPI.StringsUtil;
import com.nulldev.util.VariableAPI.util.strings.splitters.Splitters;
import com.nulldev.util.logging.Logger;
import com.nulldev.util.logging.LoggerFactory;

public class EndscreenEntry {

	private static final Logger log = LoggerFactory.getLogger();

	public static enum EntryType {
		/* Rejected: CHANNEL */
		PLAYLIST("playlist"),
		VIDEO("video"),
		WEBSITE("website"),
		UNKNOWN("n/a")

		;

		public final String id;

		private EntryType(final String id) {
			this.id = id;
		}
	}

	private final EntryType type;
	private final String videoID;
	private final String url;
	private volatile String text;
	private volatile String subText;
	private volatile String overridenImageUrl;
	private final static DecimalFormat formatter = new DecimalFormat("#,###");

	public EndscreenEntry(final EntryType type, final String url, final String videoID, final String text, final String subText) {
		this.type = type;
		this.url = url;
		this.videoID = videoID;
		this.text = StringsUtil.unescapeHtml3(text);
		this.subText = subText;
		try {
			if (this.type == EntryType.PLAYLIST && this.subText.contains(": ")) { // assuming this always present author name
				final String[] _s = Splitters.splitString(this.subText, ": ");
				this.subText = ArrayUtils.StringArrayUtils.addFrom(_s, 1);
			} else if (this.type == EntryType.VIDEO) { // assuming that this is always the view count
				this.subText = StringsUtil.onlyNumbers(subText);
				if (this.subText.endsWith(" ")) {
					this.subText = this.subText.substring(0, this.subText.length() - 1);
				}
				this.subText = this.subText.replaceAll(" ", ",");
				this.subText = formatter.format(MathUtil.safeParseL(this.subText, 0)) + " views";
			}
		} catch (Exception e) {
			log.error(e);
			this.subText = subText;
			this.text = text;
		}
	}

	public EntryType getType() {
		return this.type;
	}

	public String getVideoID() {
		return this.videoID;
	}

	public String getURL() {
		return this.url;
	}

	public String getText() {
		return this.text;
	}

	public String getSubText() {
		return this.subText;
	}

	public String getImageURL() {
		if (this.overridenImageUrl != null && !this.overridenImageUrl.isEmpty()) {
			return this.overridenImageUrl;
		} else {
			return "https://i.ytimg.com/vi/" + getVideoID() + "/mqdefault.jpg";
		}
	}

	public EndscreenEntry overrideImageURL(final String url) {
		if (url != null && !url.isEmpty()) {
			this.overridenImageUrl = url;
		}
		return this;
	}

}
